// 云函数入口文件
const cloud = require('wx-server-sdk')
const superagent = require('superagent')
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})
const db = cloud.database()

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()

  if (event.getNew) {
    //获取上课任务
    let data_ksap = await superagent
      .get(`http://8.129.187.205:3000/wyu/jwxc/ksap`)
      .then()
    let objData = JSON.parse(data_ksap.text).data
    let finalData = []

    for (const key in objData) {
      await objData[key].forEach(item => { //数据清洗
        finalData.push({
          name: item.kcmc, //课程名称
          date: item.ksrq, //日期
          time: item.kssj, //时间
          place: item.kscdmc, //地点
          term: item.xnxqdm //学期
        })
      })
    }

    try { //存入数据库
      await db.collection('user').where({
        id: wxContext.OPENID
      }).update({
        data: {
          ksap: finalData
        },
      })

    } catch (e) {
      return e
    }


    return "ok"
  } else {
    let data = await db.collection('user').where({
      id: wxContext.OPENID
    }).get()
    return data.data[0].ksap
  }
}